package cn.fx.framework.spring.web;

import cn.fx.framework.utils.StringUtils;
import cn.fx.framework.web.AbstractApplicationHandler;
import org.springframework.context.ApplicationContext;

/**
 * 默认WebApplicationHandler完成环境设置
 * 1、设置当前环境：dev、test、pre、prod，来自properties中spring.profiles.active配置；
 * 2、设置Redis缓存key的前缀，来自properties中site.redis.default-cache-prefix-keys-with
 * 3、配置Cookie的域名:来自properties中site.session.cookie-domain
 * 4、配置Cookie的Path：来自properties中site.session.cookie-path
 *
 * @author fx
 * @since 2024-11-24 14:30
 **/
public class DefaultWebApplicationHandler extends AbstractApplicationHandler {
    private String activeString;
    private String redisKeyPrefix;
    private String cookieDomain;
    private String cookiePath;

    public DefaultWebApplicationHandler(ApplicationContext applicationContext) {
        super(applicationContext);
        this.activeString = applicationContext.getEnvironment().getProperty("spring.profiles.active");
        if (StringUtils.isNullOrEmpty(activeString)) {
            this.activeString = "dev";
        }
        this.redisKeyPrefix = applicationContext.getEnvironment().getProperty("site.redis.default-cache-prefix-keys-with");
        if (StringUtils.isNullOrEmpty(this.redisKeyPrefix)) {
            this.redisKeyPrefix = "fx";
        }
        cookieDomain = applicationContext.getEnvironment().getProperty("site.session.cookie-domain");

        cookiePath = applicationContext.getEnvironment().getProperty("site.session.cookie-path");
    }

    @Override
    public String getRedisKeyPrefix() {
        return redisKeyPrefix;
    }

    /**
     * 获取当前应用运行的环境：dev/test/debug/pre/prod
     *
     * @return
     */
    @Override
    public String getCurEnvironment() {
        return activeString;
    }

    @Override
    public boolean isDevEnvironment() {
        return StringUtils.isNullOrEmpty(activeString) || activeString.equalsIgnoreCase("dev");
    }

    @Override
    public boolean isTestEnvironment() {
        //只有当spring.profiles.active系统参数配置有值且值不为prod，才判定为test
        return StringUtils.isNotEmpty(activeString) && activeString.equalsIgnoreCase("test");
    }

    @Override
    public boolean isDebugEnvironment() {
        return StringUtils.isNullOrEmpty(activeString) || activeString.equalsIgnoreCase("dev");
    }

    @Override
    public boolean isPreEnvironment() {
        return StringUtils.isNotEmpty(activeString) && activeString.equalsIgnoreCase("pre");
    }

    @Override
    public boolean isProdEnvironment() {
        return StringUtils.isNotEmpty(activeString) && activeString.equalsIgnoreCase("prod");
    }
}
